import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { updatePostSchema } from '@/lib/validations';
import { verifyToken } from '@/lib/auth';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const post = await prisma.post.findUnique({
      where: { id },
      include: {
        author: {
          select: { id: true, name: true, email: true }
        },
        tags: {
          include: {
            tag: true
          }
        },
        comments: {
          where: { status: 'APPROVED' },
          orderBy: { createdAt: 'desc' }
        }
      }
    });

    if (!post) {
      return NextResponse.json(
        { error: '文章不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      ...post,
      author: post.author.name,
      tags: post.tags.map(pt => pt.tag.name)
    });
  } catch (error) {
    console.error('获取文章失败:', error);
    return NextResponse.json(
      { error: '获取文章失败' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const authHeader = request.headers.get('authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const token = authHeader.substring(7);
    const payload = await verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { error: '无效的访问令牌' },
        { status: 401 }
      );
    }

    const body = await request.json();
    const validatedData = updatePostSchema.parse(body);

    // 检查文章是否存在
    const existingPost = await prisma.post.findUnique({
      where: { id }
    });

    if (!existingPost) {
      return NextResponse.json(
        { error: '文章不存在' },
        { status: 404 }
      );
    }

    // 如果更新了 slug，检查是否已存在
    if (validatedData.slug && validatedData.slug !== existingPost.slug) {
      const slugExists = await prisma.post.findUnique({
        where: { slug: validatedData.slug }
      });

      if (slugExists) {
        return NextResponse.json(
          { error: 'URL别名已存在' },
          { status: 400 }
        );
      }
    }

    // 处理标签更新
    let tagIds: string[] = [];
    if (validatedData.tags) {
      tagIds = await Promise.all(
        validatedData.tags.map(async (tagName) => {
          const tag = await prisma.tag.upsert({
            where: { name: tagName },
            update: {},
            create: { name: tagName }
          });
          return tag.id;
        })
      );
    }

    // 更新文章
    const updateData = {
      ...validatedData,
      publishedAt: validatedData.status === 'PUBLISHED' && existingPost.status !== 'PUBLISHED' 
        ? new Date() 
        : existingPost.publishedAt
    };

    // 移除 tags 字段，单独处理
    delete (updateData as any).tags;

    const post = await prisma.post.update({
      where: { id },
      data: updateData,
      include: {
        author: {
          select: { id: true, name: true, email: true }
        },
        tags: {
          include: {
            tag: true
          }
        }
      }
    });

    // 如果更新了标签，重新创建关联
    if (validatedData.tags) {
      await prisma.postTag.deleteMany({
        where: { postId: id }
      });

      await prisma.postTag.createMany({
        data: tagIds.map(tagId => ({
          postId: id,
          tagId
        }))
      });

      // 重新获取更新后的文章
      const updatedPost = await prisma.post.findUnique({
        where: { id },
        include: {
          author: {
            select: { id: true, name: true, email: true }
          },
          tags: {
            include: {
              tag: true
            }
          }
        }
      });

      return NextResponse.json({
        ...updatedPost,
        tags: updatedPost?.tags.map(pt => pt.tag.name) || []
      });
    }

    return NextResponse.json({
      ...post,
      author: post.author.name,
      tags: post.tags.map(pt => pt.tag.name)
    });
  } catch (error) {
    console.error('更新文章失败:', error);
    if (error instanceof Error && error.name === 'ZodError') {
      return NextResponse.json(
        { error: '数据验证失败', details: error.message },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { error: '更新文章失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // 验证管理员权限
    const token = request.cookies.get('auth-token')?.value;
    if (!token) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }

    const payload = await verifyToken(token);
    if (!payload) {
      return NextResponse.json({ error: 'Token 验证失败' }, { status: 401 });
    }
    
    if (payload.role !== 'ADMIN') {
      return NextResponse.json({ error: '权限不足' }, { status: 403 });
    }

    const { id } = await params;
    const post = await prisma.post.findUnique({
      where: { id }
    });

    if (!post) {
      return NextResponse.json(
        { error: '文章不存在' },
        { status: 404 }
      );
    }

    await prisma.post.delete({
      where: { id }
    });

    return NextResponse.json({ message: '文章删除成功' });
  } catch (error) {
    console.error('删除文章失败:', error);
    return NextResponse.json(
      { error: '删除文章失败' },
      { status: 500 }
    );
  }
}
